package com.woniuxy.customer;

import com.rabbitmq.client.Channel;
import com.woniuxy.service.SendMsgService;
import com.woniuxy.util.ConstantUtil;
import com.woniuxy.utils.PhoneBasedCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class CodeCustomer implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback{
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private RedisTemplate redisTemplateInit;
    @Resource
    private SendMsgService sendMsgService;

    @RabbitListener(queues = ConstantUtil.REGISTER_ROUTING_KEY)
    public void receiveCode(String msg, Channel channel, Message message) throws IOException {
        try {
            log.info("接收到用户手机号：{}",msg);
            String code = PhoneBasedCodeUtil.generateCode(msg, 4);
            log.info("生成四位验证码{}", code);
            redisTemplateInit.opsForValue().set(ConstantUtil.REDIS_CODE_KEY+msg,code,60, TimeUnit.SECONDS);

            // 调用短信服务发送验证码
            // 注意：这里的 "1" 是短信模板ID的占位符，您需要替换成您在云信平台申请的真实模板ID
            String templateId = "1";
            String[] params = {code, "1"}; // 参数：{验证码, 有效时间(分钟)}
            sendMsgService.sendMsg(msg, templateId, params);
            log.info("已调用短信发送服务，手机号: {}, 验证码: {}", msg, code);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            log.error("发送验证码异常", e);
        }
    }
    @Override
    public void confirm(CorrelationData correlationData, boolean flag, String s) {

    }

    @Override
    public void returnedMessage(Message message, int i, String s, String s1, String s2) {

    }
}
